package com.sdhs.paas.gateway.util;

import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public final class SpringContextUtil
{
  private static ApplicationContext context;

  private static void setApplicationContext(ApplicationContext applicationContext)
  {
    context = applicationContext;
  }

  public static <T> T getBean(String beanName)
  {
    return (T) getContext().getBean(beanName);
  }

  public static <T> T getBean(Class<T> requiredType)
  {
    return getContext().getBean(requiredType);
  }

  public static ApplicationContext getContext() {
    return context;
  }

  public static HttpServletRequest getCurrentRequest()
    throws IllegalStateException
  {
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
      throw new IllegalStateException("Current thread does not contain request context.");
    }
    return requestAttributes.getRequest();
  }

  public static class Setter
    implements ApplicationContextAware
  {
    public void setApplicationContext(ApplicationContext applicationContext)
    {
      SpringContextUtil.setApplicationContext(applicationContext);
    }
  }
}
